import request from "@/utils/request";
import {MenuQuery, MenuVo} from "@/api/sys/admin/menu/types";
import {PATH_SYS_ADMIN} from "@/utils/constant";

const baseUrl = PATH_SYS_ADMIN + '/menu/'

/**
 * 查询菜单列表
 * @param data
 */
export function getMenuListApi(data: MenuQuery): Promise<MenuVo[]> {
    return request.post(baseUrl + 'list', data)
}

/**
 * 通过菜单id获取菜单信息
 * @param id
 */
export function getMenuByIdApi(id: number): Promise<MenuVo> {
    return request.get(baseUrl + id)
}

/**
 * 修改菜单
 * @param id
 * @param data
 */
export function editMenuApi(id: number | string, data: MenuVo): Promise<any> {
    return request.patch(baseUrl + id, handleData(data))

}

/**
 * 添加菜单
 * @param data
 */
export function addMenuApi(data: MenuVo): Promise<any> {
    return request.post(baseUrl, handleData(data))
}

function handleData(data: MenuVo) {
    // 菜单类型(1:菜单；2:目录；3:按钮；4:外链)
    // 每个类型传递哪些属性
    const {
        name, type, path, component,
        perm, status, parent,
        icon, sort, redirect, remark
    } = data
    let tempData: MenuVo = {parent, name, type, sort, status, remark} // 公共属性
    if (type === 1) {
        tempData = {...tempData, icon, path, component}
    } else if (type === 2) {
        tempData = {...tempData, icon, path, redirect}
    } else if (type === 3) {
        tempData = {...tempData, perm}
    } else if (type === 4) {
        tempData = {...tempData, icon, path}
    }
    return tempData
}

/**
 * 删除菜单
 * @param id
 */
export function deleteMenuApi(id: number): Promise<any> {
    return request.delete(baseUrl + id)
}

/**
 * 获取菜单的树状结构(只包含菜单和目录)
 * 用在菜单添加/编辑时,上面的父级菜单栏
 */
export function getMenuTreeApi(): Promise<MenuVo[]> {
    return request.get(baseUrl + 'select')
}

/**
 * 获取菜单的树状结构,包含全部类型
 * 用在角色分 配/选择 菜单时候的菜单树
 */
export function getAllotMenuTreeApi(): Promise<MenuVo[]> {
    return request.get(baseUrl + 'allot')
}

